<template>
  <div class="notification-page">
    <a-page-header title="系统通知" sub-title="管理和发送系统通知消息">
      <template #extra>
        <a-space>
          <a-button type="primary" @click="handleCreate">
            <template #icon><plus-outlined /></template>
            新建通知
          </a-button>
          <a-button 
            :disabled="!selectedRowKeys.length"
            @click="handleBatchSend"
          >
            <template #icon><send-outlined /></template>
            批量发送
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <!-- 统计卡片 -->
    <a-row :gutter="16" class="stats-row">
      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic 
            title="总通知数" 
            :value="stats.total"
            :value-style="{ color: '#3f8600' }"
          >
            <template #prefix><notification-outlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic 
            title="已发送" 
            :value="stats.sent"
            :value-style="{ color: '#1890ff' }"
          >
            <template #prefix><check-circle-outlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic 
            title="待发送" 
            :value="stats.pending"
            :value-style="{ color: '#faad14' }"
          >
            <template #prefix><clock-circle-outlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic 
            title="今日发送" 
            :value="stats.todaySent"
            :value-style="{ color: '#722ed1' }"
          >
            <template #prefix><rocket-outlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 搜索筛选 -->
    <a-card class="search-card card-shadow">
      <a-form layout="inline">
        <a-form-item label="通知类型">
          <a-select 
            v-model:value="searchForm.type" 
            placeholder="请选择" 
            style="width: 150px"
            allowClear
          >
            <a-select-option value="SYSTEM">系统通知</a-select-option>
            <a-select-option value="ACTIVITY">活动通知</a-select-option>
            <a-select-option value="ANNOUNCEMENT">公告通知</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="状态">
          <a-select 
            v-model:value="searchForm.status" 
            placeholder="请选择" 
            style="width: 120px"
            allowClear
          >
            <a-select-option value="DRAFT">草稿</a-select-option>
            <a-select-option value="PENDING">待发送</a-select-option>
            <a-select-option value="SENT">已发送</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="关键词">
          <a-input 
            v-model:value="searchForm.keyword" 
            placeholder="标题/内容"
            style="width: 200px"
            allowClear
          />
        </a-form-item>
        
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon><reload-outlined /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 数据表格 -->
    <a-card class="table-card card-shadow">
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        @change="handleTableChange"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <a-tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'priority'">
            <a-tag :color="getPriorityColor(record.priority)">
              {{ getPriorityText(record.priority) }}
            </a-tag>
          </template>
          
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'targetUsers'">
            <a-tooltip>
              <template #title>{{ record.targetUsers }}</template>
              <span>{{ getTargetUsersText(record.targetUsers) }}</span>
            </a-tooltip>
          </template>
          
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button 
                type="link" 
                size="small" 
                @click="handleView(record)"
              >
                查看
              </a-button>
              <a-button 
                type="link" 
                size="small" 
                @click="handleEdit(record)"
                v-if="record.status === 'DRAFT'"
              >
                编辑
              </a-button>
              <a-button 
                type="link" 
                size="small" 
                @click="handleSend(record)"
                v-if="record.status === 'PENDING' || record.status === 'DRAFT'"
              >
                发送
              </a-button>
              <a-popconfirm
                title="确定要删除这条通知吗？"
                @confirm="handleDelete(record)"
              >
                <a-button 
                  type="link" 
                  size="small" 
                  danger
                  v-if="record.status === 'DRAFT'"
                >
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新建/编辑通知弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      width="800px"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-item label="通知标题" name="title">
          <a-input v-model:value="formData.title" placeholder="请输入通知标题" />
        </a-form-item>

        <a-form-item label="通知类型" name="type">
          <a-select v-model:value="formData.type" placeholder="请选择通知类型">
            <a-select-option value="SYSTEM">系统通知</a-select-option>
            <a-select-option value="ACTIVITY">活动通知</a-select-option>
            <a-select-option value="ANNOUNCEMENT">公告通知</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="优先级" name="priority">
          <a-select v-model:value="formData.priority" placeholder="请选择优先级">
            <a-select-option value="LOW">低</a-select-option>
            <a-select-option value="NORMAL">普通</a-select-option>
            <a-select-option value="HIGH">高</a-select-option>
            <a-select-option value="URGENT">紧急</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="目标用户" name="targetUsers">
          <a-select v-model:value="formData.targetUsers" placeholder="请选择目标用户">
            <a-select-option value="ALL">全部用户</a-select-option>
            <a-select-option value="TEACHER">所有教员</a-select-option>
            <a-select-option value="PARENT">所有家长</a-select-option>
            <a-select-option value="CUSTOM">指定用户</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item 
          label="用户ID" 
          name="userIds"
          v-if="formData.targetUsers === 'CUSTOM'"
        >
          <a-input 
            v-model:value="formData.userIds" 
            placeholder="多个用户ID用逗号分隔，如：1,2,3"
          />
        </a-form-item>

        <a-form-item label="通知内容" name="content">
          <a-textarea 
            v-model:value="formData.content" 
            placeholder="请输入通知内容"
            :rows="6"
            :maxlength="500"
            show-count
          />
        </a-form-item>

        <a-form-item label="定时发送">
          <a-switch v-model:checked="formData.scheduled" />
          <span style="margin-left: 10px; color: #999;">开启后可设置发送时间</span>
        </a-form-item>

        <a-form-item 
          label="发送时间" 
          name="sendTime"
          v-if="formData.scheduled"
        >
          <a-date-picker 
            v-model:value="formData.sendTime" 
            show-time 
            format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item label="链接地址">
          <a-input 
            v-model:value="formData.linkUrl" 
            placeholder="点击通知跳转的链接（选填）"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 查看通知详情弹窗 -->
    <a-modal
      v-model:open="viewModalVisible"
      title="通知详情"
      width="700px"
      :footer="null"
    >
      <a-descriptions bordered :column="2">
        <a-descriptions-item label="标题" :span="2">
          {{ viewData.title }}
        </a-descriptions-item>
        <a-descriptions-item label="类型">
          <a-tag :color="getTypeColor(viewData.type)">
            {{ getTypeText(viewData.type) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="优先级">
          <a-tag :color="getPriorityColor(viewData.priority)">
            {{ getPriorityText(viewData.priority) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getStatusColor(viewData.status)">
            {{ getStatusText(viewData.status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="目标用户">
          {{ getTargetUsersText(viewData.targetUsers) }}
        </a-descriptions-item>
        <a-descriptions-item label="内容" :span="2">
          {{ viewData.content }}
        </a-descriptions-item>
        <a-descriptions-item label="已读人数">
          {{ viewData.readCount || 0 }}
        </a-descriptions-item>
        <a-descriptions-item label="发送人数">
          {{ viewData.sendCount || 0 }}
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">
          {{ viewData.createdAt }}
        </a-descriptions-item>
        <a-descriptions-item label="发送时间">
          {{ viewData.sentAt || '未发送' }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  SendOutlined,
  NotificationOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  RocketOutlined,
  SearchOutlined,
  ReloadOutlined
} from '@ant-design/icons-vue'
import {
  getNotificationList,
  createNotification,
  updateNotification,
  deleteNotification,
  sendNotification,
  batchSendNotifications,
  getNotificationStats
} from '@/api/notification'

// 统计数据
const stats = reactive({
  total: 0,
  sent: 0,
  pending: 0,
  todaySent: 0
})

// 搜索表单
const searchForm = reactive({
  type: undefined,
  status: undefined,
  keyword: ''
})

// 表格配置
const loading = ref(false)
const dataSource = ref([])
const selectedRowKeys = ref([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`
})

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 60 },
  { title: '标题', dataIndex: 'title', key: 'title', width: 200 },
  { title: '类型', key: 'type', width: 100 },
  { title: '优先级', key: 'priority', width: 90 },
  { title: '目标用户', key: 'targetUsers', width: 120 },
  { title: '状态', key: 'status', width: 90 },
  { title: '阅读数', dataIndex: 'readCount', key: 'readCount', width: 80 },
  { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt', width: 160 },
  { title: '操作', key: 'action', width: 220, fixed: 'right' }
]

const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  }
}

// 弹窗配置
const modalVisible = ref(false)
const modalTitle = ref('新建通知')
const formRef = ref()
const formData = reactive({
  id: null,
  title: '',
  type: 'SYSTEM',
  priority: 'NORMAL',
  targetUsers: 'ALL',
  userIds: '',
  content: '',
  scheduled: false,
  sendTime: null,
  linkUrl: ''
})

const rules = {
  title: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择通知类型', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  targetUsers: [{ required: true, message: '请选择目标用户', trigger: 'change' }],
  content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }]
}

// 查看详情
const viewModalVisible = ref(false)
const viewData = reactive({})

// 初始化
onMounted(() => {
  loadData()
  loadStats()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await getNotificationList({
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    })
    if (res.code === 200) {
      dataSource.value = res.data.records || []
      pagination.total = res.data.total || 0
    }
  } catch (error) {
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载统计
const loadStats = async () => {
  try {
    const res = await getNotificationStats()
    if (res.code === 200) {
      Object.assign(stats, res.data)
    }
  } catch (error) {
    console.error('加载统计失败', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    type: undefined,
    status: undefined,
    keyword: ''
  })
  handleSearch()
}

// 表格变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadData()
}

// 新建
const handleCreate = () => {
  modalTitle.value = '新建通知'
  resetForm()
  modalVisible.value = true
}

// 编辑
const handleEdit = (record) => {
  modalTitle.value = '编辑通知'
  Object.assign(formData, record)
  modalVisible.value = true
}

// 查看
const handleView = (record) => {
  Object.assign(viewData, record)
  viewModalVisible.value = true
}

// 发送
const handleSend = async (record) => {
  try {
    const res = await sendNotification(record.id)
    if (res.code === 200) {
      message.success('发送成功')
      loadData()
      loadStats()
    }
  } catch (error) {
    message.error('发送失败')
  }
}

// 批量发送
const handleBatchSend = async () => {
  try {
    const res = await batchSendNotifications(selectedRowKeys.value)
    if (res.code === 200) {
      message.success('批量发送成功')
      selectedRowKeys.value = []
      loadData()
      loadStats()
    }
  } catch (error) {
    message.error('批量发送失败')
  }
}

// 删除
const handleDelete = async (record) => {
  try {
    const res = await deleteNotification(record.id)
    if (res.code === 200) {
      message.success('删除成功')
      loadData()
      loadStats()
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    const api = formData.id ? updateNotification : createNotification
    const params = formData.id ? [formData.id, formData] : [formData]
    
    const res = await api(...params)
    if (res.code === 200) {
      message.success(formData.id ? '更新成功' : '创建成功')
      modalVisible.value = false
      loadData()
      loadStats()
    }
  } catch (error) {
    console.error('提交失败', error)
  }
}

// 取消
const handleCancel = () => {
  modalVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    title: '',
    type: 'SYSTEM',
    priority: 'NORMAL',
    targetUsers: 'ALL',
    userIds: '',
    content: '',
    scheduled: false,
    sendTime: null,
    linkUrl: ''
  })
  formRef.value?.resetFields()
}

// 辅助方法
const getTypeColor = (type) => {
  const colors = {
    SYSTEM: 'blue',
    ACTIVITY: 'green',
    ANNOUNCEMENT: 'orange'
  }
  return colors[type] || 'default'
}

const getTypeText = (type) => {
  const texts = {
    SYSTEM: '系统通知',
    ACTIVITY: '活动通知',
    ANNOUNCEMENT: '公告通知'
  }
  return texts[type] || type
}

const getPriorityColor = (priority) => {
  const colors = {
    LOW: 'default',
    NORMAL: 'blue',
    HIGH: 'orange',
    URGENT: 'red'
  }
  return colors[priority] || 'default'
}

const getPriorityText = (priority) => {
  const texts = {
    LOW: '低',
    NORMAL: '普通',
    HIGH: '高',
    URGENT: '紧急'
  }
  return texts[priority] || priority
}

const getStatusColor = (status) => {
  const colors = {
    DRAFT: 'default',
    PENDING: 'orange',
    SENT: 'green'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    DRAFT: '草稿',
    PENDING: '待发送',
    SENT: '已发送'
  }
  return texts[status] || status
}

const getTargetUsersText = (target) => {
  const texts = {
    ALL: '全部用户',
    TEACHER: '所有教员',
    PARENT: '所有家长',
    CUSTOM: '指定用户'
  }
  return texts[target] || target
}
</script>

<style lang="scss" scoped>
.notification-page {
  .stats-row {
    margin-bottom: 16px;

    .stat-card {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    }
  }

  .search-card,
  .table-card {
    margin-bottom: 16px;
  }

  .card-shadow {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }
}
</style>

